package com.zqc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqc.common.R;
import com.zqc.dto.SetmealDto;
import com.zqc.entity.Category;
import com.zqc.entity.Dish;
import com.zqc.entity.Setmeal;
import com.zqc.entity.SetmealDish;
import com.zqc.service.CategoryService;
import com.zqc.service.DishService;
import com.zqc.service.SetMealDishService;
import com.zqc.service.SetMealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    public SetMealService setMealService;

    @Autowired
    public SetMealDishService setMealDishService;

    @Autowired
    public CategoryService categoryService;

    @Autowired
    public DishService dishService;

    /**
     * 保存套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setMealCache", allEntries = true) // 清除setMealCache空间的所有缓存
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setMealService.saveSetmealAndDish(setmealDto);
        return R.success("套餐添加成功");
    }

    /**
     * 页面需要套餐分类的名称，通过setmeal实体查询的分页数据不包含套餐分类名称，需要进行数据对象的转换
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 构造分页构造器
        Page<Setmeal> setmealPage = new Page<>();
        Page<SetmealDto> setmealDtoPage = new Page<>();
        // 查询分页数据
        setMealService.page(setmealPage, new LambdaQueryWrapper<Setmeal>()
                .like(name != null, Setmeal::getName, name)
                .orderByAsc(Setmeal::getUpdateTime)
        );

        // 对象拷贝
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        // 对分页数据进行处理
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> setmealDtoList = records.stream().map(item -> {
            // 对象拷贝
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            // 查询分类对象
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            // 设置CategoryName
            setmealDto.setCategoryName(category.getName());

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtoList);

        // 将转换数据返回
        return R.success(setmealDtoPage);
    }

    /**
     * 根据id查询具体套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getOne(@PathVariable(name = "id") Long id) {
        SetmealDto setmealDto = setMealService.getSetMealInfo(id);
        return R.success(setmealDto);
    }

    /**
     * 更新套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setMealCache", allEntries = true) // 清除setMealCache空间的所有缓存
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setMealService.updateStemealAndDish(setmealDto);
        return R.success("套餐修改成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setMealCache", allEntries = true) // 清除setMealCache空间的所有缓存
    public R<String> delete(Long[] ids) {
        setMealService.removeSetMealAndDish(ids);
        return R.success("套餐删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "setMealCache", allEntries = true) // 清除setMealCache空间的所有缓存
    public R<String> updateStatus(@PathVariable(name = "status") int status, Long[] ids) {
        setMealService.update(new UpdateWrapper<Setmeal>().in("id", ids).set("status", status));
        return R.success("套餐状态修改成功");
    }

    /**
     * 根据套餐分类id条件查询套餐信息
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setMealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        List<Setmeal> setmeals = setMealService.list(new LambdaQueryWrapper<Setmeal>()
                .eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus())
                .orderByAsc(Setmeal::getUpdateTime));
        return R.success(setmeals);
    }

    /**
     * 查看套餐详情
     *
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<Dish>> dish(@PathVariable(name = "id") Long setMealId) {
        // 根据套餐id查询套餐菜品信息
        List<SetmealDish> setmealDishes = setMealDishService.list(new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId, setMealId));
        // 封装菜品id查询菜品信息
        ArrayList<Long> dishIds = (ArrayList<Long>) setmealDishes.stream().map(item -> {
            Long dishId = item.getDishId();
            return dishId;
        }).collect(Collectors.toList());

        // 通过id列表查询菜品信息
        List<Dish> dishList = dishService.listByIds(dishIds);
        return R.success(dishList);
    }

}
